package com.loong.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.loong.framework.handler.MultiTenantHandler;
import com.loong.framework.properties.TenantProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@MapperScan("com.loong.*.mapper")
@EnableTransactionManagement(proxyTargetClass = true)
@EnableConfigurationProperties(TenantProperties.class)
public class MyBatisPlusConfig {

  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor(TenantProperties tenantProperties) {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

    if (Boolean.TRUE.equals(tenantProperties.getEnable())) {
      // 启用多租户插件拦截
      interceptor.addInnerInterceptor(
          new TenantLineInnerInterceptor(new MultiTenantHandler(tenantProperties)));
    }

    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    return interceptor;
  }
}
